<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="contractStartTime">
        <el-date-picker clearable
                        v-model="queryParams.contractStartTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="contractEndTime">
        <el-date-picker clearable
                        v-model="queryParams.contractEndTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="contactName">
        <el-input
            v-model="queryParams.contactName"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
            v-model="queryParams.contactInfo"
            placeholder="请输入联系方式"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属" prop="attribution">
        <el-select v-model="queryParams.attribution" placeholder="请选择归属" clearable>
          <el-option
              v-for="dict in partners_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:sysPartners:add']"
        >新增
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="info"-->
<!--            plain-->
<!--            icon="Sort"-->
<!--            @click="toggleExpandAll"-->
<!--        >展开/折叠-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="sysPartnersList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="名称" width="150" prop="name"/>
      <el-table-column label="签约年限" width="100" align="center" prop="contractYears"/>
      <el-table-column label="签约时间" align="center" prop="contractTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contractTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签约时间范围" align="center" prop="contractStartTime" width="300">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.contractStartTime, '{y}-{m}-{d}')
            }}-{{ parseTime(scope.row.contractEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150" align="center" prop="contactName"/>
      <el-table-column label="联系方式" width="200" align="center" prop="contactInfo"/>
      <el-table-column label="归属" width="100" align="center" prop="attribution">
        <template #default="scope">
          <dict-tag :options="partners_type" :value="scope.row.attribution"/>
        </template>
      </el-table-column>
      <el-table-column label="抽成比例" width="100" align="center" prop="commissionRateValue"/>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:sysPartners:edit']">修改
          </el-button>
          <!--          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:sysPartners:add']">新增</el-button>-->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:sysPartners:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改合伙人列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="sysPartnersRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" maxlength="10"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签约起始" prop="contractStartTime">
              <el-date-picker
                  clearable
                  v-model="contractTimeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  @change="handleContractTimeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="签约时间" prop="contractTime">
              <el-date-picker clearable
                              v-model="form.contractTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="选择签约时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签约年限" prop="contractYears">
              <el-input v-model="form.contractYears" placeholder="请输入签约年限" :readonly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入姓名" maxlength="10"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input v-model="form.contactInfo" placeholder="请输入联系方式"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属" prop="attribution">
              <el-select v-model="form.attribution" placeholder="请选择归属">
                <el-option
                    v-for="dict in partners_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市" prop="cityCode">
              <el-cascader-city v-model="form.cityCode" :is-save="true"></el-cascader-city>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

<!--          <el-col :span="12">-->
<!--            <el-form-item label="抽成比例" prop="commissionRate">-->
<!--              <el-input v-model="form.commissionRate" placeholder="请输入抽成比例"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysPartners">
import {
  listSysPartners,
  getSysPartners,
  delSysPartners,
  addSysPartners,
  updateSysPartners
} from "@/api/system/sysPartners";
import useUserStore from '@/store/modules/user'
import {watch} from "vue";

const {proxy} = getCurrentInstance();
const {partners_type} = proxy.useDict('partners_type');

const sysPartnersList = ref([]);
const sysPartnersOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);
const contractTimeRange = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    name: null,
    contractStartTime: null,
    contractEndTime: null,
    contactName: null,
    contactInfo: null,
    attribution: null,
    cityCode: null
  },
  rules: {
    name: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    contractYears: [
      {required: true, message: "签约年限不能为空", trigger: "blur"}
    ],
    contractTime: [
      {required: true, message: "签约时间不能为空", trigger: "blur"}
    ],
    contactName: [
      {required: true, message: "姓名不能为空", trigger: "blur"},
      { validator: validateChineseCharacters, message:"姓名只能输入1-5个汉字", trigger: "blur" }
    ],
    contactInfo: [
      {required: true, message: "联系方式不能为空", trigger: "blur"},
      {pattern: /^(1[3|4|5|6|7|8|9]\d{9})$|^(\d{3,4}-\d{7,8})$/, message: "请输入正确的手机号码", trigger: "blur"}
    ],
    contractStartTime: [
      {required: true, message: "请选择起始时间", trigger: "blur"}
    ],
    cityCode: [
      {required: true, message: "请选择省市", trigger: "blur"}
    ],
    attribution:[
      {required: true, message: "请选择归属", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询合伙人列表列表 */
function getList() {
  loading.value = true;
  listSysPartners(queryParams.value).then(response => {
    sysPartnersList.value = proxy.handleTree(response.data, "id", "parentId");
    loading.value = false;
  });
}

function validateChineseCharacters(rule, value, callback) {
  const pattern = /^[\u4e00-\u9fa5]{1,5}$/; // Chinese character pattern
  if (!pattern.test(value)) {
    callback(new Error("姓名只能输入1-5个汉字"));
  } else {
    callback();
  }
}

/** 查询合伙人列表下拉树结构 */
function getTreeselect() {
  listSysPartners().then(response => {
    sysPartnersOptions.value = [];
    const data = {id: 0, name: '顶级节点', children: []};
    data.children = proxy.handleTree(response.data, "id", "parentId");
    sysPartnersOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    cityCode: null,
    parentId: null,
    leve: null,
    contractYears: null,
    contractTime: null,
    contractStartTime: null,
    contractEndTime: null,
    contactName: null,
    contactInfo: null,
    attribution: null,
    commissionRate: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  contractTimeRange.value =[];
  proxy.resetForm("sysPartnersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加合伙人列表";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.id;
  }
  getSysPartners(row.id).then(response => {
    contractTimeRange.value = [response.data.contractStartTime, response.data.contractEndTime];
    form.value = response.data;
    open.value = true;
    title.value = "修改合伙人列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sysPartnersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSysPartners(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          useUserStore().cascaderKey += 1;
        });
      } else {
        addSysPartners(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该数据项？').then(function () {
    return delSysPartners(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleContractTimeChange(value) {
  if (value && value.length === 2) {
    form.value.contractStartTime = value[0];
    form.value.contractEndTime = value[1];

    const startDate = new Date(value[0]);
    const endDate = new Date(value[1]);

    const MS_PER_MONTH = 1000 * 60 * 60 * 24 * 30.4375;

    const timeDifference = endDate - startDate;
    const monthsDifference = timeDifference / MS_PER_MONTH;

    if (monthsDifference >= 12) {
      const years = Math.floor(monthsDifference / 12);
      const remainingMonths = Math.floor(monthsDifference % 12);

      if (remainingMonths > 0) {
        form.value.contractYears = `${years}年${remainingMonths}个月`;
      } else {
        form.value.contractYears = `${years}年`;
      }
    } else {
      form.value.contractYears = `${Math.floor(monthsDifference)}个月`;
    }
  }
}



getList();
watch(() => useUserStore().cascaderKey, (v) => {
  getList();
}, { immediate: true });
</script>
